var tablink = "";
var docsurl = "https://docs.google.com/";
var errormessage = "";
var password = "";
var resourceid = "";
var title = "";
var content = "";
var messagefromserver = "";
var util = {};
var bgPage = chrome.extension.getBackgroundPage();
var selectedTab = 0;
var encryption_algo = "";

util.setNewErrorMessage = function (message) {
    $("#new_error_message").text(message);
    $("#new_error_message_div").show();
}

util.hideNewErrorMessage = function () {
    $("#new_error_message").text("");
    $("#new_error_message_div").hide();
}

util.setExistingErrorMessage = function (message) {
    $("#existing_error_message").text(message);
    $("#existing_error_message_div").show();
}

util.hideExistingErrorMessage = function () {
    $("#existing_error_message").text("");
    $("#existing_error_message_div").hide();
}

util.reset = function(){
	errormessage = "";
	$("#existing_error_message").text("");
    $("#existing_error_message_div").hide();
    $("#new_error_message").text("");
    $("#new_error_message_div").hide();
    $("#create_progress_text").text("");
	$("#create_progress_bar").hide();
	$("#title").val("");
	$("#content").val("");
	$("#enpassword").val("");
	$("#decontent").val("");
	$("#depassword").val("");
	$("#hmac").val("");
	$("#hmacdiv").hide();
}

util.setEncryptionAlgo = function(algo){
	encryption_algo = algo;
}

util.getEncryptionAlgo = function(){
	return encryption_algo;
}

/**
 * Urlencodes a JSON object of key/value query parameters.
 * @param {Object} parameters Key value pairs representing URL parameters.
 * @return {string} query parameters concatenated together.
 */
util.stringify = function (parameters) {
    var params = [];
    for (var p in parameters) {
        params.push(encodeURIComponent(p) + '=' + encodeURIComponent(parameters[p]));
    }
    return params.join('&');
};

/**
 * Creates a JSON object of key/value pairs
 * @param {string} paramStr A string of Url query parmeters.
 *    For example: max-results=5&startindex=2&showfolders=true
 * @return {Object} The query parameters as key/value pairs.
 */
util.unstringify = function (paramStr) {
    var parts = paramStr.split('&');

    var params = {};
    for (var i = 0, pair; pair = parts[i]; ++i) {
        var param = pair.split('=');
        params[decodeURIComponent(param[0])] = decodeURIComponent(param[1]);
    }
    return params;
};

util.setProgressBar = function(step, text){
	$("#create_progress_bar").show();
	$("#create_progress_bar").progressbar({value: step});
	$("#create_progress_text").text(text);
}

util.hideProgressBar = function(step, text){
	$("#create_progress_text").text("");
	$("#create_progress_bar").hide();
}

$(document).ready(function () {
    /**
     * Get authorization from the user to play with his/her google docs
     * The call back for this function is empty
     * If we already have the authorizaion, then this does nothing
     */
    bgPage.oauth.authorize(function () {});
    
    /**
     * When user clicks the encrypt button
     * find out if the user is on an open doc page and has entered a password for encryption
     */
    $("#enbutton").click(function () {
		errormessage = "";
        if ($("#enpassword").val() == "") {
            errormessage = "Please enter a password to encrypt with!";
        } else if($("#title").val() == ""){
        	errormessage = "Please enter a title for the document!";
        } else if($("#content").val() == ""){
        	errormessage = "Please enter content to encrypt!";
        } 
        if (errormessage == "") {
        	title = $("#title").val();
        	content = $("#content").val();
            password = $("#enpassword").val();
            enalgo = $("#enalgo").children(":selected").attr("id");
            console.log("encryption algorith: "+enalgo);
            util.hideNewErrorMessage();
            util.setProgressBar(20, "encrypting");
            var encryptedContent = "";
            if(enalgo == "aes"){
           		encryptedContent = ejUtil.aes_encrypt(password, content);
           	}else if(enalgo == "des"){
           		encryptedContent = ejUtil.des_encrypt(password, content);
           	}else if(enalgo == "3des"){
           		encryptedContent = ejUtil.trides_encrypt(password, content);	
           	}else if(enalgo == "rabbit"){
           		encryptedContent = ejUtil.rabbit_encrypt(password, content);
           	}else if(enalgo == "rc4"){
           		encryptedContent = ejUtil.rc4_encrypt(password, content);
           	}
            console.log(encryptedContent);
            util.setProgressBar(40, "creating doc");
			gdocs.createDoc(title, encryptedContent);
			util.setProgressBar(100, "done, encrypted doc created");
			$("#title").val("");
			$("#content").val("");
			$("#enpassword").val("");
        }else{
        	util.hideProgressBar();
            util.setNewErrorMessage(errormessage);
        }
    });
    
    $("#debutton").click(function() {
    	errormessage = "";
    	if($("#debutton").val() == "Decrypt"){
    		if($("#depassword").val() == ""){
    			errormessage = "Please enter a password to decrypt with!";
    		}
    	
    		if(errormessage == ""){
    			util.hideExistingErrorMessage();
    			password = $("#depassword").val();
    			content = $("#decontent").val();
    			encryption_algo = content.substring(0,1);
    			content = content.substring(1, content.length);
    			util.setEncryptionAlgo(encryption_algo);
    			console.log(encryption_algo);
    			console.log(content);
    			var decryptedText = "";
    			if(encryption_algo == "0"){
    				decryptedText = ejUtil.aes_decrypt(password, content);
    				console.log("decryptedText: "+decryptedText);
    				//Extract message and hmac, then recalculate hmac and compare to hmac

					var str_array = decryptedText.split(" ");
					
					//There is a junk hash at the end, I believe to be from HMAC calculation of SHA256(K^ipad || message) where ^ is xor operation
					//var junkHash = str_array.pop();
					
					//Get the HMAC
					var hmac1 = str_array.pop();
					console.log("hmac1: "+hmac1);
					//Plaintext with HMAC stripped
					var msg = str_array.join(" ");
					console.log("msg: "+msg); 
					//Recalculated HMAC
					var hmac2 = ejUtil.generate_hmac(password, msg);
					console.log("hmac2: "+hmac2);
					
					$("#hmacdiv").show();
					
					//Was the HMAC clean?
					if(hmac1 == hmac2)
						$("#hmac").val("HMAC is clean.");
					else
						$("#hmac").val("ALERT: WRONG HMAC, do not trust message!");//Message was tampered with!
					decryptedText = msg;
    			}
    			else if(encryption_algo == "1")
    				decryptedText = ejUtil.des_decrypt(password, content);
    			else if(encryption_algo == "2")
    				decryptedText = ejUtil.trides_decrypt(password, content);
    			else if(encryption_algo == "3")
    				decryptedText = ejUtil.rabbit_decrypt(password, content);
    			else if(encryption_algo == "4")
    				decryptedText = ejUtil.rc4_decrypt(password, content);

    			if(decryptedText == ""){
					errormessage = "Incorrect password or content!";
					util.setExistingErrorMessage(errormessage);
				}else{
					$("#decontent").val(decryptedText);
					$("#decontent").removeAttr("disabled");			
					$("#debutton").val("Update");
				}
			}else{
				util.setExistingErrorMessage(errormessage);
			}
    	}else{
    		$("#hmac").val("");
    		if($("#depassword").val() == ""){
    			errormessage = "Please enter a password to update with!";
    		}
    		if(errormessage == ""){
    			password = $("#depassword").val();
    			content = $("#decontent").val();
    			console.log("edit index: "+editindex);
    			var updatedDoc = bgPage.docs[editindex];
    			var encryptedContent = "";
    			console.log("encryption algo: "+encryption_algo);
    			if(util.getEncryptionAlgo()=="0")
    				encryptedContent = ejUtil.aes_encrypt(password, content);
    			else if(util.getEncryptionAlgo()=="1")
    				encryptedContent = ejUtil.des_encrypt(password, content);
    			else if(util.getEncryptionAlgo()=="2")
    				encryptedContent = ejUtil.trides_encrypt(password, content);
    			else if(util.getEncryptionAlgo()=="3")
    				encryptedContent = ejUtil.rabbit_encrypt(password, content);
    			else if(util.getEncryptionAlgo()=="4")
    				encryptedContent = ejUtil.rc4_encrypt(password, content);
    			updatedDoc.content = encryptedContent;
    			console.log(updatedDoc.content);
    			gdocs.updateDoc(updatedDoc);
    			$("#decontent").attr("disabled", "true");
    			$("#debutton").val("Decrypt");
    			$("#decontent").val("Update finished");
    			$("#depassword").val("");
    		}
    	}
    });

    $("#tabs").bind('tabsselect', function (event, ui) {
    	util.reset();
        if (ui.index == 1) {
        	util.hideProgressBar();
            gdocs.getDocumentList();
        }
    });
});
